package com.inifitness.admin.core.config.redis;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis 缓存配置
 *
 * @author sunjinfeng
 * @since 2023/12/4
 */
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@ConditionalOnProperty(name = "spring.cache.enabled") // xxl.job.enabled = true 才会自动装配
public class RedisCacheConfig {

  private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(
      "yyyy-MM-dd HH:mm:ss");
  private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

  /**
   * 自定义 RedisTemplate
   * <p>
   * 修改 Redis 序列化方式，默认 JdkSerializationRedisSerializer
   *
   * @param redisConnectionFactory {@link RedisConnectionFactory}
   * @return {@link RedisTemplate}
   */
  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory,
      Jackson2JsonRedisSerializer<?> jackson2JsonRedisSerializer,
      StringRedisSerializer stringRedisSerializer) {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(redisConnectionFactory);
    // key采用String的序列化方式
    redisTemplate.setKeySerializer(stringRedisSerializer);
    // hash的key也采用String的序列化方式
    redisTemplate.setHashKeySerializer(stringRedisSerializer);
    // value序列化方式采用jackson
    redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
    // hash的value序列化方式采用jackson
    redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
  }


  /**
   * 自定义 RedisCacheManager
   * <p>
   * 修改 Redis 序列化方式，默认 JdkSerializationRedisSerializer
   *
   * @param redisConnectionFactory {@link RedisConnectionFactory}
   * @param cacheProperties        {@link CacheProperties}
   * @return {@link RedisCacheManager}
   */
  @Bean
  public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory,
      CacheProperties cacheProperties, Jackson2JsonRedisSerializer<?> jackson2JsonRedisSerializer,
      StringRedisSerializer stringRedisSerializer) {
    return RedisCacheManager.builder(
            RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
        .cacheDefaults(redisCacheConfiguration(cacheProperties, jackson2JsonRedisSerializer,
            stringRedisSerializer))
        .build();
  }

  /**
   * 自定义 RedisCacheConfiguration
   *
   * @param cacheProperties {@link CacheProperties}
   * @return {@link RedisCacheConfiguration}
   */
  @Bean
  RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties,
      Jackson2JsonRedisSerializer<?> jackson2JsonRedisSerializer,
      StringRedisSerializer stringRedisSerializer) {
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
    config = config.serializeKeysWith(
        RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer));
    config = config.serializeValuesWith(
        RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
    CacheProperties.Redis redisProperties = cacheProperties.getRedis();
    if (redisProperties.getTimeToLive() != null) {
      config = config.entryTtl(redisProperties.getTimeToLive());
    }
    if (!redisProperties.isCacheNullValues()) {
      config = config.disableCachingNullValues();
    }
    if (!redisProperties.isUseKeyPrefix()) {
      config = config.disableKeyPrefix();
    }
    //覆盖默认key双冒号  CacheKeyPrefix#prefixed
    config = config.computePrefixWith(name -> name + ":");
    return config;
  }

  @Bean
  Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
        ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

    //LocalDatetime序列化
    JavaTimeModule timeModule = new JavaTimeModule();
    timeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(dateFormatter));
    timeModule.addDeserializer(LocalDateTime.class,
        new LocalDateTimeDeserializer(dateTimeFormatter));
    timeModule.addSerializer(LocalDate.class, new LocalDateSerializer(dateFormatter));
    timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
    om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    om.registerModule(timeModule);
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
        om, Object.class);
    return jackson2JsonRedisSerializer;
  }

  @Bean
  StringRedisSerializer stringRedisSerializer() {
    return new StringRedisSerializer();
  }
}
